<template>
  <t-form
    ref="formRef"
    :data="assessOptionDetail"
    :requiredMark="false"
    labelAlign="top"
    @submit="onSubmit"
  >
    <div
      class="upload-container"
      :class="isDetail ? 'upload-con2' : 'upload-con1'"
    >
      <!-- 左侧菜单 -->
      <t-menu
        class="upload-container__menu"
        theme="light"
        :expanded="expandedKeys"
        @expand="handleExpand"
        @change="handleMenuChange"
        v-model:value="defaultValue"
      >
        <t-submenu
          mode="popup"
          v-for="item in assessOptionDetail"
          :key="item.id"
          :value="item.id"
        >
          <template #title>
            <span>{{ item.name }}</span>
          </template>
          <t-menu-item
            v-for="child in item?.child"
            :key="child.id"
            :value="child.optionsCode"
          >
            {{ child.name }}</t-menu-item
          >
        </t-submenu>
      </t-menu>
      <t-divider class="upload-container__line" layout="vertical" />
      <!-- 右侧内容 -->
      <div
        class="upload-container__up"
        ref="scrollContainer"
        @scroll.passive="handleScroll"
      >
        <div
          v-for="item in assessOptionDetail"
          :key="item.optionsCode"
        >
          <div class="title" :id="item.child[0].optionsCode">
            {{ item.name }}
          </div>
          <div
            v-for="child in item.child"
            :id="child.optionsCode"
            :key="child.optionsCode"
          >
            <div class="sub-title">{{ child.name }}</div>
            <div
              v-for="grandson in child.child"
              :key="grandson.optionsCode"
              class="form-container"
            >
              <div class="txt-name">
                {{ grandson.name }}
                <t-popup v-if="grandson?.ms" :content="grandson.ms"
                  :overlay-style="{ maxWidth: '480px' }"><icon style="cursor: pointer" name="info-circle"
                /></t-popup>
              </div>
              <div class="txt-label">资料是否可提供</div>
              <!-- 0  可提供    1  不可提供  -->
              <t-radio-group v-model="grandson.sfsy" :disabled="isDetail || grandson?.sfhg === 0 ">
                <t-radio :value="0">可提供</t-radio>
                <t-radio :value="1">不可提供</t-radio>
              </t-radio-group>
              <t-textarea
                v-if="grandson.sfsy === 1"
                class="reason-input"
                :class="
                  isShowValidate && !grandson.bsyReason ? 'validate-input' : ''
                "
                v-model="grandson.bsyReason"
                placeholder="请输入不可提供的原因"
                @enter="onEnter"
                autosize
                :disabled="grandson?.sfhg === 0 || isDetail"
              />
              <div
                v-if="
                  grandson.sfsy === 1 && isShowValidate && !grandson.bsyReason
                "
                class="file-validate"
              >
                请填写不可提供原因
              </div>
              <!-- <div v-if="approvalStatus == 0 && grandson.sfsy === 0 || (submitProcess > 4 && grandson.sfsy === 0)">
                <t-upload
                  ref="uploadRef"
                  class="up-container"
                  v-model="grandson.optionsFileList"
                  theme="file-flow"
                  multiple
                  name="files"
                  :headers="{ authorization: token }"
                  :action="url"
                  placeholder="支持批量上传文件，文件格式不限，最多只能上传 5 份文件"
                  :abridge-name="[6, 6]"
                  :auto-upload="autoUpload"
                  :max="5"
                  :sizeLimit="{ size: 10, unit: 'MB', message: '文件大小不能超过10MB' }"
                  :disabled="grandson?.sfhg === 0 "
                  @fail="handleFail"
                  @remove="handleRemove"
                  :onValidate="handleValidate"
                > -->
              <!--  @selectChange="changeSelect(grandson)" -->
              <!-- @progress="handleProgress(grandson, $event)" -->
                
                <!-- </t-upload> -->
                <!-- <div
                  class="file-container"
                  v-for="(item, index) in grandson.optionsFileList"
                  :key="index"
                >
                  <span class="file-container__name">{{item.fileName}}</span>
                  <icon name="download" size="16" color="#0052D9" @click="downloadFile(item.sjhgPath)"></icon>
                </div> -->
              <!-- </div> -->

              <!-- 打回标红 -->
              <!-- :class="approvalStatus === 1 ?'up-red':''" -->            
              <!-- v-if="approvalStatus != 0 && grandson.sfsy === 0" -->
              <t-upload
                ref="uploadRef"
                class="up-container"
                v-if="grandson.sfsy === 0"
                v-model="grandson.optionsFileList"
                theme="file-flow"
                multiple
                name="files"
                :headers="{ authorization: token }"
                :action="url"
                placeholder="支持批量上传文件，文件格式不限，最多只能上传 5 份文件"
                :abridge-name="[6, 6]"
                :auto-upload="autoUpload"
                :max="5"
                :sizeLimit="{ size: 10, unit: 'MB', message: '文件大小不能超过10MB' }"
                :disabled="approvalStatus == 0 || grandson?.sfhg === 0 "
                @fail="handleFail"
                @remove="handleRemove"
                :onValidate="handleValidate"
              >
              <!--  @selectChange="changeSelect(grandson)" -->
              <!-- @progress="handleProgress(grandson, $event)" -->
                <template   
                    v-if="approvalStatus == 0 && grandson.sfsy === 0 || (submitProcess > 4 && grandson.sfsy === 0)"                 
                      #fileListDisplay="{ files }"
                    >
                      <div class="custom-upload-display">
                        <div class="upload-table">
                          <div class="upload-table-header">
                            <div style="width: 34%">文件名</div>
                            <div style="width: 23%">大小</div>
                            <div style="width: 23%">状态</div>
                            <div style="width: 20%">操作</div>
                          </div>
                          <div class="upload-table-body">
                            <div
                              v-for="(file, index) in files"
                              :key="index"
                              class="upload-table-row"
                            >
                              <div class="table-cell" style="width: 34%">
                                <span class="file-name table-txt">{{
                                  file.name
                                }}</span>
                              </div>
                              <div class="table-txt" style="width: 23%">
                                {{ formatFileSize(file.size) }}
                              </div>
                              <div
                                class="table-txt txt-center"
                                style="width: 23%"
                              >
                                <img
                                  class="table-success"
                                  src="@/assets/image/success.png"
                                  alt=""
                                />
                                <span class="table-txt" style="margin-left: 8px"
                                  >上传成功</span
                                >
                              </div>
                              <div style="width: 20%">
                                <t-button
                                  style="padding: 0"
                                  variant="text"
                                  size="small"
                                  theme="primary"
                                  @click="handlePreview(file)"
                                  :disabled="getFileType(file) === 'unknown'"
                                >
                                  预览
                                </t-button>
                                <t-button
                                  style="margin-left: 10px; padding: 0"
                                  variant="text"
                                  size="small"
                                  theme="primary"
                                  @click="downloadFile(file.sjhgPath)"
                                >
                                  下载
                                </t-button>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                </template>
              </t-upload>
             
              <div
                v-if="
                  grandson.sfsy === 0 &&
                  isShowValidate &&
                  (!grandson.optionsFileList ||
                    grandson.optionsFileList?.length <= 0)
                "
                class="file-validate"
              >
                请上传文件
              </div>
              <!-- 0  合格   1  不合格 -->
              <div class="assessment-result" v-if="grandson?.sfhg!==null && grandson?.sfhg !== 0 ">
                <div class="assessment-result__con">
                  评估意见 <span>{{['','部分符合要求','不符合要求'][grandson?.sfhg]}}</span>
                </div>
                <div class="assessment-result__desc">
                  意见说明 <span>{{ grandson.bhgReason }}</span>
                </div>
              </div>
              <div v-if="grandson?.sfhg === 0 ">
                <div class="assessment-ok" >
                  <div class="assessment-ok__con">评估意见 <span>完全符合要求</span></div>
                  <div class="assessment-result__desc">
                     意见说明 <span>{{ grandson.bhgReason }}</span>
                  </div>
                </div>
              </div>
              
            </div>
          </div>
        </div>
      </div>
      <!-- 底部按钮 -->
      <div class="fixed-container" v-if="!isDetail">
        <!-- "isReturn 0 不是打回   1 打回") -->
        <t-checkbox
          v-model:checked="isShowDH"
          class="checkbox"
          v-if="approvalStatus === 1"
          @change="showDHChange"
          >只看打回项目</t-checkbox
        >
        <span v-else></span>
        <t-space :size="8" class="fixed-container__btn">
          <t-popup
            showArrow
            destroy-on-close
            trigger="click"
            class="popup"
            :visible="popupVisible"
            width="280px"
          >
            <template #content>
              <div class="title-container">
                <div class="title-container__title" v-if="noTBDataCount">
                  你还有{{ noTBDataCount }}个必填项目未填
                </div>
                <icon name="close" size="20px" @click="onToggle" />
              </div>
              <div class="anchor-container" v-if="noTBData">
                <div v-for="item in noTBData" :key="item.optionsCode">
                  <div class="anchor-container__name">{{ item.name }}</div>
                  <t-menu
                    v-model:value="defaultValue"
                    @change="handleMenuChange2"
                  >
                    <t-menu-item
                      v-for="child in item.child"
                      :key="child.optionsCode"
                      :value="child.optionsCode"
                    >
                      {{ child.name }}
                      <template #icon v-if="defaultValue === child.optionsCode">
                        <img
                          class="anchor-container__img"
                          src="@/assets/image/anchor.png"
                          alt=""
                        />
                      </template>
                    </t-menu-item>
                  </t-menu>
                </div>
              </div>
            </template>
            <div class="tx-txt" @click="onToggle" v-if="noTBDataCount">
              <img class="img" src="@/assets/image/tx.svg" />
              <span class="tx-con">还有{{ noTBDataCount }}必填项未填</span>
            </div>
          </t-popup>
          <t-form-item>
            <t-space :size="8">
              <t-button theme="default" variant="outline" @click="clickCancel"
                >取消</t-button
              >
              <t-button theme="default" variant="outline" @click="clickSave"
                >保存</t-button
              >
              <t-button theme="primary" type="submit">提交</t-button>
            </t-space>
          </t-form-item>
        </t-space>
      </div>
    </div>
  </t-form>
  <!-- 弹框 -->
  <t-dialog
    v-model:visible="cancelVisible"
    theme="warning"
    header="确定取消吗？"
    body="您还未完成项目填写，确定取消吗？取消后填写数据将不会被保存"
    :on-close="cancelClose"
    @confirm="cancelConfirm"
    confirm-btn="确定"
  />

  <t-dialog
    v-model:visible="saveVisible"
    theme="warning"
    header="确认保存吗？"
    body="请确认保存信息"
    :on-close="saveClose"
    @confirm="saveConfirm"
    confirm-btn="确认"
  />
  <t-dialog
    v-model:visible="submitVisible"
    theme="warning"
    header="确认提交吗？"
    body="请确认提交信息"
    :on-close="submitClose"
    @confirm="submitConfirm"
    confirm-btn="确认"
  />
  <div class="t">
    <t-dialog
      class="preview-wrapper"
      header="文件预览"
      :visible="bodyVisible"
      :onClose="bodyClose"
      :onConfirm="bodyClose"
      :footer="false"
      :dialogStyle="{
        width: '70vw', // 支持百分比/vw单位
        maxWidth: 'none', // 禁用最大宽度限制
      }"
    >
      <div slot="body">
        <div v-if="fileData">
          <!-- Word 预览 -->
          <div v-if="fileType === 'word'" class="docx-preview">
            <VueOfficeDocx
              :src="fileData"
              @rendered="handleRendered"
              @error="handleError"
            />
          </div>

          <!-- Excel 预览 -->
          <div v-if="fileType === 'excel'" class="excel-preview">
            <VueOfficeExcel
              :src="fileData"
              @rendered="handleRendered"
              @error="handleError"
            />
          </div>

          <!-- PDF 预览 -->
          <div v-if="fileType === 'pdf'" class="pdf-preview">
            <VuePdfEmbed
              :source="fileData"
              @rendered="handleRendered"
              @error="handleError"
            />
          </div>
        </div>
      </div>
    </t-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, reactive } from "vue";
import { Icon } from "tdesign-icons-vue-next";
import { getAssessOptionDetail, submitAssess } from "@/api/sjhg/assess";
import { MessagePlugin } from "tdesign-vue-next";
import { useRouter } from "vue-router";
import { getToken } from "@/utils/auth";
import { downloadFile2 } from '@/api/sjhg/upload'; 
import VueOfficeDocx from "@vue-office/docx";
import VueOfficeExcel from "@vue-office/excel";
import VuePdfEmbed from "vue-pdf-embed";
import "@vue-office/docx/lib/index.css";
import "@vue-office/excel/lib/index.css";

const router = useRouter();
const props = defineProps({
  assessId: {
    type: String,
    default: "",
  },
  approvalStatus: {
    type: Number,
    default: 0,
  },
  submitProcess: {
    type: Number,
    default: 0,
  },
});
//增加文件超出5个提示
const handleValidate = (files) => {
  if(files.type === 'FILES_OVER_LENGTH_LIMIT'){
    MessagePlugin.warning('最多只能上传 5 个文件');
  }
};
const isShowValidate = ref(false);
const isShowDH = ref(false);
const originalData = reactive([]);
const showDHChange = (val) => {
  if (val == true) {
    //只看打回
    const filterDHData = assessOptionDetail
    .map((p) => ({
      ...p,
      child: (p?.child || [])
        .map((c) => ({
          ...c,
          child: (c?.child || []).filter((g) => {
            return g.sfhg !== 0;
          }),
        }))
        .filter((c) => (c?.child || []).length > 0), // 保留有孙子节点的子节点
    }))
    .filter((p) => (p?.child || []).length > 0); // 保留有子节点的父节点
    //审核打回的数据
    updateAssessOptionDetail(filterDHData)
    // Object.assign(assessOptionDetail, filterDHData);
    defaultValue.value = filterDHData[0].child[0].optionsCode;
  } else {
    updateAssessOptionDetail(originalData)
    // Object.assign(assessOptionDetail, originalData);
  }
};

//更新数据
const updateAssessOptionDetail = (filteredData) => {
  // 清空数组
  assessOptionDetail.splice(0, assessOptionDetail.length);
  // 重新填充
  filteredData.forEach(item => assessOptionDetail.push(item));
};

//-----------------文件上传----------------------------
const url = window.lwConfig.services.auth + "/sjhg/multi/upload";
const autoUpload = ref(true);
const isDetail = ref(false);
isDetail.value =
  props.submitProcess > 4 ||
  (props.submitProcess === 4 && props.approvalStatus === 0);
const token = "Bearer " + getToken();
const handleFail = ({ file }) => {
  MessagePlugin.error(`文件 ${file.name} 上传失败`);
};

//资料填报显示项
const assessOptionDetail = reactive([]);
//------未填报数据+数量--------------
const noTBData = reactive([]);
const noTBDataCount = ref(0);

//--------------锚点----------------
const scrollContainer = ref(null);
let observer = null;
const defaultValue = ref(null); //默认选中menu
const formRef = ref(null);

const popupVisible = ref(false);
//关闭或展示popup
const onToggle = () => {
  popupVisible.value = !popupVisible.value;
};
const expandedKeys = ref([])

  // 菜单展开/收起回调
const handleExpand = (keys) => {
  console.log('当前展开的菜单:', keys);
  expandedKeys.value = keys;
};

// status 0 暂存   1提交
const formData = ref({
  assessId: props.assessId,
  assessItemList: null,
  status: 1,
});

const uploadRef = ref(null);
const handleRemove = (file) => {
  // 终止该文件的上传任务
  if (file.status != 'success') {
    console.log('文件正在上传不允许删除')
    return
  }
};
//------------------------获取未填报项--------------------------------------
//未填报数据
const handleNoTB = () => {
  console.log("--assessOptionDetail---->", assessOptionDetail);
  const filteredData = assessOptionDetail
  .map((p) => ({
      ...p,
      child: (p?.child || [])
        .map((c) => ({
          ...c,
          child: (c?.child || []).filter((g) => {
            if (g.sfsy === 0) {
              return !g.optionsFileList || g.optionsFileList.length === 0;
            } else if (g.sfsy === 1) {
              return !g.bsyReason || g.bsyReason === "";
            }
            return false; // 其他情况不保留
          }),
        }))
        .filter((c) => (c?.child || []).length > 0), // 保留有孙子节点的子节点
    }))
    .filter((p) => (p?.child || []).length > 0); // 保留有子节点的父节点
  //未填报赋值
  console.log("filteredData===>", filteredData);
  // 调用
  updateNoTBData(filteredData);
  // Object.assign(noTBData, filteredData);
  const getchildrenData = noTBData
    .flatMap((parent) => parent.child || []) // 获取所有子级
    .flatMap((child) => child.child || []) // 获取所有孙子级
    .map((grandchild) => ({
      optionsCode: grandchild.optionsCode,
    }));
  noTBDataCount.value = getchildrenData?.length;
};
//更新数据
const updateNoTBData = (filteredData) => {
  // 清空数组
    noTBData.splice(0, noTBData.length);
    // 重新填充
    filteredData.forEach(item => noTBData.push(item));
};
//------------------------------------------提交--------------------------------------------
const submitVisible = ref(false)
const submitClose = () =>{
  saveVisible.value = false
}
const submitConfirm = () =>{
  // ---------提交接口----------------
  if (isShowDH.value) {
      //如果是打回
      // updateDHData()
      console.log("originalData===>", originalData);
      const grandchildrenData = originalData
        .flatMap((parent) => parent.child || []) // 获取所有子级
        .flatMap((child) => child.child || []) // 获取所有孙子级
        .map((grandchild) => ({
          optionsCode: grandchild.optionsCode,
          sfsy: grandchild.sfsy,
          files: handleOptionFileList(grandchild.optionsFileList),
          reason: grandchild.bsyReason,
        }));
      formData.value.assessItemList = grandchildrenData;
    } else {
      const grandchildrenData = assessOptionDetail
        .flatMap((parent) => parent.child || []) // 获取所有子级
        .flatMap((child) => child.child || []) // 获取所有孙子级
        .map((grandchild) => ({
          optionsCode: grandchild.optionsCode,
          sfsy: grandchild.sfsy,
          files: handleOptionFileList(grandchild.optionsFileList),
          reason: grandchild.bsyReason,
        }));
      formData.value.assessItemList = grandchildrenData;
    }
  submitAssess(formData.value)
      .then((res) => {
        if (res.code == 200) {
          MessagePlugin.success(res.msg);
          //成功后跳转到列表
          router.push({ path: "/home/index" });
          isShowValidate.value = false;
        } else {
          MessagePlugin.error(res.msg);
        }
      })
      .finally(() => {});
}
const onSubmit = async () => {
  isShowValidate.value = true;
  await handleNoTB();
  if (noTBDataCount.value === 0) {
    //提交弹框显示  关闭未填报导航
    popupVisible.value = false
    submitVisible.value = true
  }else {
    MessagePlugin.warning(`还有${noTBDataCount.value}必填项未填，请填完后再提交`)
  }
};
//-----------------------------------暂存---------------------------------------------------
const saveVisible = ref(false)
const saveClose = () =>{
  saveVisible.value = false
}
const saveConfirm = () =>{
  formData.value.status = 0;
  if (isShowDH.value) {
    //如果是打回
    // updateDHData()
    console.log("originalData===>", originalData);
    const grandchildrenData = originalData
      .flatMap((parent) => parent.child || []) // 获取所有子级
      .flatMap((child) => child.child || []) // 获取所有孙子级
      .map((grandchild) => ({
        optionsCode: grandchild.optionsCode,
        sfsy: grandchild.sfsy,
        files: handleOptionFileList(grandchild.optionsFileList),
        reason: grandchild.bsyReason,
      }));
    formData.value.assessItemList = grandchildrenData;
  } else {
    const grandchildrenData = assessOptionDetail
      .flatMap((parent) => parent.child || []) // 获取所有子级
      .flatMap((child) => child.child || []) // 获取所有孙子级
      .map((grandchild) => ({
        optionsCode: grandchild.optionsCode,
        sfsy: grandchild.sfsy,
        files: handleOptionFileList(grandchild.optionsFileList),
        reason: grandchild.bsyReason,
      }));
    formData.value.assessItemList = grandchildrenData;
  }
  submitAssess(formData.value)
    .then((res) => {
      if (res.code == 200) {
        MessagePlugin.success(res.msg);
        //成功后跳转到列表
        router.push({ path: "/home/index" });
      } else {
        MessagePlugin.error(res.msg);
      }
    })
    .finally(() => {});
}
const clickSave = () => {
  popupVisible.value = false
  saveVisible.value = true
};

// 文件列表处理
const handleOptionFileList = (files) => {
  var newFiles = []
  files.forEach(item => {
    if (item.raw) {
      newFiles.push(...item.response.data)
    } else {
      newFiles.push(item)
    }
  });
  return newFiles
}

// 菜单点击处理
const handleMenuChange = (val) => {
  const target = document.getElementById(val);
  if (target) {
    target.scrollIntoView({ behavior: "smooth", block: "start" });
  }
};
// 菜单点击处理
const handleMenuChange2 = (val) => {
  const target = document.getElementById(val);
  if (target) {
    target.scrollIntoView({ behavior: "smooth", block: "start" });
  }
  onToggle();
};

////资料取消弹框
const cancelVisible = ref(false);
//点击取消按钮
const clickCancel = () => {
  cancelVisible.value = true;
};
//弹框的取消
const cancelClose = () => {
  popupVisible.value = false
  cancelVisible.value = false;
};
//弹框的确定事件
const cancelConfirm = () => {
  router.push({ path: "/home/index" });
};
//----------------------------锚点处理逻辑--------------------------------------
onBeforeUnmount(() => {
  if (observer) observer.disconnect();
});
onMounted(async() => {
  await getOptionDetail();
  initIntersectionObserver();
});
// 初始化观察器‌:ml-citation{ref="3,6" data="citationList"}
const initIntersectionObserver = () => {
  const options = {
    root: scrollContainer.value, // 观察元素的根元素，null表示视窗
    threshold: 0.5, // 交叉比例的阈值，0.5表示元素一半进入视窗时触发回调
    rootMargin: "0px", // 根元素的边界
  };

  observer = new IntersectionObserver((entries) => {
    entries.forEach((entry) => {
      if (entry.isIntersecting) {
        //元素进入视框
        // activeAnchor.value = entry.target.id
        console.log("entry.target.id====>", entry.target.id);
        defaultValue.value = entry.target.id;
      }
    });
  }, options);

  assessOptionDetail.forEach((item) => {
    item.child.forEach((child) => {
      const el = document.getElementById(child.optionsCode);
      if (el) observer.observe(el);
    });
  });
};

//-------------------------接口--------------------------------------
const getOptionDetail = () => {
  let params = {};
  params.assessId = props.assessId;
  getAssessOptionDetail(params)
    .then((res) => {
      if (res.code == 200) {
        // reactive 赋值方式
        Object.assign(originalData, res.data);
        Object.assign(assessOptionDetail, res.data);
        defaultValue.value = res.data[0].child[0].optionsCode;
        expandedKeys.value = assessOptionDetail.map(item => item.id);
      }
    })
    .finally(() => {});
};

//--------------------文件上传--------------------------

//---------------文件预览--------------------
//文件预览弹框
const bodyVisible = ref(false);

const bodyClose = () => {
  bodyVisible.value = false;
};

// 响应式数据
const fileData = ref(null);
const fileType = ref("");
const loading = ref(false);
const error = ref("");

const formatFileSize = (size) => {
  if (!size) return "0 B";
  if (size < 1024) return `${size} B`;
  if (size < 1024 * 1024) return `${(size / 1024).toFixed(2)} KB`;
  return `${(size / (1024 * 1024)).toFixed(2)} MB`;
};

// 判断文件类型（扩展名 + MIME类型双校验）
const getFileType = (file) => {
  console.log("file---->", file);

  const extension = file.name.split(".").pop().toLowerCase();
  // const mime = file.type.toLowerCase()
  // , 'doc'
  if (["docx"].includes(extension)) {
    return "word";
  }
  // , 'xls', 'csv'
  // if (['xlsx'].includes(extension) ) {
  //   return 'excel'
  // }
  if (extension === "pdf") {
    return "pdf";
  }
  return "unknown";
};

// 渲染完成回调
const handleRendered = () => {
  console.log(`${fileType.value.toUpperCase()}渲染完成`);
};

// 错误处理
const handleError = (err) => {
  error.value = `预览失败: ${err.message || "未知错误"}`;
};

// 重置状态
const resetState = () => {
  fileData.value = null;
  fileType.value = "";
  error.value = "";
};

const handlePreview = async (file) => {
  bodyVisible.value = true;
  //---------------1 url图片预览---------------------------
  if (!file.url) return;
  resetState();
  loading.value = true;

  try {
    // 1. 通过fetch获取文件Blob
    const response = await fetch(file.url);
    if (!response.ok) throw new Error("文件下载失败");
    const blob = await response.blob();
    // 2. 判断文件类型
    fileType.value = getFileType(file);
    if (!fileType.value) {
      throw new Error("不支持的文件类型");
    }
    // 3. 将Blob转为ArrayBuffer
    fileData.value = await blob.arrayBuffer();
  } catch (err) {
    error.value = err.message;
  } finally {
    loading.value = false;
  }
};


// ------------------- 下载 ---------------------
const downloadFile = async (objectPath) => {
  try {
    // const response = await axios.get('/sjhg/minio/download', {
    //   params: { bucketName: bucket, objectPath },
    //   responseType: 'blob'
    // });

    var params = {}
    params.objectPath = objectPath
    const response = await downloadFile2(params);

    // 生成临时下载链接
    const url = window.URL.createObjectURL(new Blob([response]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', objectPath.split('/').pop() || 'file');
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  } catch (error) {
    console.error('下载失败:', error);
  }
};
</script>

<style lang="scss" scoped>
:deep(.t-upload__flow-placeholder ){
  font-family: PingFang SC-Bold, PingFang SC;
  font-weight: 400;
  color: #00000066 !important;
  font-size: 12px !important;
}
:deep(.t-upload__flow-empty ){
  font-family: PingFang SC-Bold, PingFang SC;
  font-weight: 400;
  color: #00000066 !important;
  font-size: 12px !important;
}
.file-validate {
  color: #d54941;
  font-size: 12px;
  font-weight: 400;
}
.form-container {
  :deep(.t-form__label) {
    color: #4e5969;
    font-size: 14px;
    font-weight: 400;
  }
}
.content-wrapper {
  flex: 1;
  height: 100%;
  overflow-y: auto;
  padding: 20px;
}

.anchor-section {
  min-height: 600px;
  margin-bottom: 40px;
  padding: 20px;
  border: 1px solid #eee;
}
.assessment-result {
  width: 100%;
  border-radius: 12px;
  border: 1px solid rgba(0, 0, 0, 0.12);
  background: rgba(255, 64, 80, 0.08);
  padding: 16px;
  color: var(--light-text-color-text-2, #4e5969);
  font-size: 14px;
  font-weight: 400;
  font-family: PingFang SC-Bold, PingFang SC;
  line-height: 22px; /* 157.143% */
  &__desc {
    margin-top: 12px;
  }
  span {
    margin-left: 16px;
  }
}
.assessment-ok {
  width: 100%;
  border-radius: 8px;
  border: 1px solid rgba(0, 0, 0, 0.12);
  background: rgba(0, 0, 0, 0.02);
  padding: 16px;
  color: var(--light-text-color-text-2, #4e5969);
  font-size: 14px;
  font-weight: 400;
  font-family: PingFang SC-Bold, PingFang SC;
  line-height: 22px; /* 157.143% */
  &__desc {
    margin-left: 16px;
  }
}
// :deep(.t-anchor .t-is-active > a){
//   color: #0052D9;
// }
// :deep(.t-anchor__line){
//   background-color: #fff;
// }
// :deep(.t-anchor__item) {
//     --level: 0;
//     height: 28px;
// }
.anchor-container {
  min-width: 280px;
  max-height: 500px; /* 根据需求调整高度 */
  overflow-y: auto;  /* 启用垂直滚动 */
  overflow-x: hidden;
  padding: 0 8px;
  position: relative;

  :deep(.t-menu__content) {
      font-family: PingFang SC-Bold, PingFang SC;
      font-size: 14px;
      font-weight: 400;
      margin-left: 8px;
  }
    
  :deep(.t-default-menu .t-menu__item) {
    padding: 0;
    color: #000000E5;
    font-weight: 500;
  }
  :deep(.t-menu__item.t-is-active) {
    width: 280px;
    color: var(--td-brand-color);
    background-color: var(--td-brand-color-light);
  }
  &__img {
    width: 12px;
    height: 12px;
    position: absolute;
    right: 8px;
  }
  :deep(.t-default-menu__inner .t-menu) {
    padding: 0;
  }
  :deep(.t-menu) {
    width: 280px;
    margin-left: -8px;
  }
  &__name {
    height: 28px;
    line-height: 28px;
    margin-top: 3px;
    font-weight: 400;
    font-size: 14px;
    color: #00000042;
  }
}
.popup {
  padding: 6px;
}
.title-container {
  display: flex;
  justify-content: space-between;
  border-bottom: 1px solid #e7e7e7;
  padding: 3px 8px;
  &__title {
    height: 28px;
    font-size: 16px;
    line-height: 28px;
    color: #000000e5;
    font-family: PingFang SC-Bold, PingFang SC;
    font-weight: 500;
  }
}
.fixed-container {
  height: 72px;
  position: fixed;
  bottom: 0;
  right: 0;
  left: 196px;
  border-bottom-left-radius: 16px;
  border-bottom-right-radius: 16px;
  background: #fff;
  box-shadow: 1px 0px 1px 0px rgba(0, 0, 0, 0.25);
  display: flex;
  justify-content: space-between;
  align-items: center;
  .checkbox {
    margin-left: 270px;
  }
  &__btn {
    margin-right: 20px;
  }
  .tx-txt {
    display: flex;
    justify-content: flex-end;
  }
  .tx-con {
    color: #00000073;
    font-family: PingFang SC-Bold, PingFang SC;
    font-size: 16px;
    font-weight: 400;
  }
  .img {
    margin-right: 5px;
  }
}
:deep(.t-upload__flow-empty) {
  color: rgba(0, 0, 0, 0.4);
  font-size: 14px;
}
:deep(.el-input__wrapper) {
  background-color: #f2f3f5 !important;
  box-shadow: none;
  height: 32px;
}
:deep(.el-input__inner) {
  min-width: 40vw;
  height: 32px;
  line-height: 32px;
  color: #86909c;
}
.up-red{
  :deep(.t-upload__flow-table > thead > tr > th){
    border: none;
  }
  :deep(.t-upload__flow-table ){
    margin-top: 16px;
    border: 1px dashed #d54941;
  }
  :deep(.t-upload__flow-table > thead > tr){
    border-top: 1px dashed #d54941;
  }
  :deep(.t-button--variant-text.t-button--theme-primary ){
    color: #d54941;
  }
  :deep(.t-upload__flow-table > tbody > tr > td){
    color: #d54941;
  }
  :deep(.t-upload__flow-table > tbody > tr ){
    border-top: 1px dashed #d54941;
  }
  :deep(.t-link--theme-default ){
    color:#d54941;
  }
}
.up-container {
  margin-top: 8px;
  margin-bottom: 20px;
  :deep(.t-upload__flow-table > thead > tr > th){
    border: none;
  }
}
.title {
  color: #292b33;
  font-size: 18px;
  line-height: 24px;
  margin-top: 16px;
  letter-spacing: 0.5px;
  font-weight: 500;
  font-family: PingFang SC-Bold, PingFang SC;
}
.sub-title {
  font-size: 16px;
  color: #565960;
  position: relative;
  padding-left: 8px;
  margin-top: 24px;
  font-weight: 500;
  font-family: PingFang SC-Bold, PingFang SC;

  &::before {
    content: ""; /* 在内容前添加竖线 */
    position: absolute;
    width: 3px;
    height: 18px;
    border-radius: 3px;
    background-color: #1966ff;
    left: 0;
    top: 2px;
    -webkit-border-radius: 3px;
    -moz-border-radius: 3px;
    border-radius: 3px;
  }
}
.txt-name {
  color: #565960;
  font-size: 14px;
  line-height: 22px;
  margin-top: 16px;
  font-weight: 500;
  font-family: PingFang SC-Bold, PingFang SC;
}
.txt-label {
  color: #4e5969;
  font-size: 14px;
  font-weight: 400;
  line-height: 22px;
  margin-top: 8px;
  margin-bottom: 4px;
  font-family: PingFang SC-Bold, PingFang SC;
}
.reason-input {
  margin: 8px 0;
  :deep(.t-textarea__inner ){
    background-color: #f2f3f5;
    border: 1px solid #f2f3f5;
    border-radius: 2px;
  }
  :deep(.t-textarea__inner:focus){
    box-shadow: none;
  }
}
.validate-input {
  border: 1px solid #d54941;
  border-radius: 4px;
}
.upload-con1 {
  margin-bottom: 60px;
  height: calc(100vh - 288px);
}
.upload-con2 {
  margin-bottom: 0px;
  height: calc(100vh - 230px);
}
.upload-container {
  position: relative;
  display: flex;
  &__menu {
    position: sticky;
    top: 0;
    margin-top: -16px;

    :deep(.t-menu__content) {
      font-family: PingFang SC-Bold, PingFang SC;
      font-size: 14px;
      font-weight: 400;
      span{
        font-weight: 600;
        color: #292B33;
      }
    }
    :deep(.t-default-menu__inner .t-menu) {
      padding: 0;
      margin-top: 8px;
    }
    :deep(.t-default-menu .t-menu__item.t-is-active:not(.t-is-opened)) {
      color: #1966ff;
    }
    :deep(.t-divider--vertical) {
      margin: 0;
    }
    :deep(.t-default-menu__inner .t-menu--scroll) {
      overflow-y: auto;
      -ms-overflow-style: none;
      scrollbar-width: none;
    }
  }
  &__line {
    height: calc(100% + 20px);
    width: 2px;
    margin-top: -16px;
  }
  &__up {
    margin: 0 16px;
    flex-grow: 1; /* 让内容区域填充剩余空间 */
    overflow-y: auto; /* 内容区域允许垂直滚动 */
    margin-top: -16px;

    :deep(.t-is-error .t-input__extra) {
      z-index: 99;
    }
    :depp(.t-upload__tips) {
      display: inline;
    }
  }
  &__up::-webkit-scrollbar {
    display: none;
  }

  //隐藏滚动条
  &__up {
    -ms-overflow-style: none;
    scrollbar-width: none;
  }
  &__menu::-webkit-scrollbar {
    display: none;
  }
  &__menu {
    -ms-overflow-style: none;
    scrollbar-width: none;
  }
}

.file-container {
  margin: 8px 0;
  height: 20px;
  display: flex;
  align-items: center;
  cursor: pointer;
  &__name {
    font-size: 12px;
    color: #00000066;
    margin-right: 8px;
    font-weight: 400;
    font-family: PingFang SC-Bold, PingFang SC;
  }
}
</style>
